package com.qcorm.core;

import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 *
 */
public class DBUtil {
	private String driver;
	private String url;
	private String username;
	private String password;
	private Connection con;
	private PreparedStatement pstmt;

	public void setDriver(String driver) {
		this.driver = driver;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	static Logger logger = Logger.getLogger(BaseDao.class.getName());

	/**
	 * 此处的连接串应该改成可以配置的
	 * @param dbType
	 * @param dbName
	 */
	public DBUtil(String dbType,String dbName) {
		if("MySql".equals(dbType)){
			driver = "com.mysql.jdbc.Driver";
			url = "jdbc:mysql://localhost:3306/"+dbName+"?useUnicode=true&characterEncoding=GBK";
			username = "root";
			this.password = "123";
		}else{
			driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
			url = "jdbc:sqlserver://localhost:55111;DatabaseName="+dbName;
			username = "*";
			this.password = "*";
		}
		
		
	}

	public void init() {
		try {
			Class.forName(driver);
			con = DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException e) {
			logger.error("init exception",e);
		} catch (SQLException e) {
			logger.error("init exception",e);
		}

	}

	public void close() {
		if (pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				logger.error("close exception", e);
			}
		}
		if (con != null) {
			try {
				con.close();
			} catch (SQLException e) {
				logger.error("close exception", e);
			}
		}
	}

	/**
	 *
	 * @param params
	 */
	public void setParams(List<DaoParameter> params) {
		if (params != null) {
			int parameterIndex = 1;
			for (DaoParameter parameter : params) {
				try {
					pstmt.setObject(parameterIndex, parameter.getParameterValue(),
							parameter.getTargetSqlTtype());
				} catch (SQLException e) {
					logger.error("setParams exception", e);
				} finally {
					parameterIndex++;
				}
			}
		}
	}

	/**
	 * 
	 * @param sql
	 * @param params
	 * @return
	 */
	public ResultSet executeQuery(String sql, List<DaoParameter> params) {
		ResultSet rs = null;
		init();
		try {
			pstmt = con.prepareStatement(sql);

			setParams(params);
			rs = pstmt.executeQuery();
		} catch (SQLException e) {
			logger.error("executeQuery exception", e);
		}

		return rs;

	}

	public int executeUpdate(String sql, List<DaoParameter> params) {
		int result = 0;
		init();
		try {
			pstmt = con.prepareStatement(sql);

			setParams(params);
			result = pstmt.executeUpdate();
		} catch (SQLException e) {
			logger.error("executeUpdate exception", e);
		}
		return result;

	}
}
